﻿using System;
using System.Windows;
using System.Windows.Controls;

namespace TrackMe.View.Behaviours
{
    /// <summary>
    /// Exposes attached behaviors that can be
    /// applied to ListBoxItem objects.
    /// </summary>
    public static class ListBoxItemBehavior
    {
        #region IsBroughtIntoViewWhenSelected

        public static bool GetIsBroughtIntoViewWhenSelected(ListBoxItem ListBoxItem)
        {
            return (bool)ListBoxItem.GetValue(IsBroughtIntoViewWhenSelectedProperty);
        }

		public static void SetIsBroughtIntoViewWhenSelected(ListBoxItem ListBoxItem, bool value)
        {
            ListBoxItem.SetValue(IsBroughtIntoViewWhenSelectedProperty, value);
        }

        public static readonly DependencyProperty IsBroughtIntoViewWhenSelectedProperty =
            DependencyProperty.RegisterAttached(
            "IsBroughtIntoViewWhenSelected",
            typeof(bool),
            typeof(ListBoxItemBehavior),
            new UIPropertyMetadata(false, OnIsBroughtIntoViewWhenSelectedChanged));

        static void OnIsBroughtIntoViewWhenSelectedChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
        {
            var item = depObj as ListBoxItem;
            if (item == null)
                return;

            if (e.NewValue is bool == false)
                return;

            if ((bool)e.NewValue)
                item.Selected += OnListBoxItemSelected;
            else
                item.Selected -= OnListBoxItemSelected;
        }

        static void OnListBoxItemSelected(object sender, RoutedEventArgs e)
        {
            // Only react to the Selected event raised by the ListBoxItem
            // whose IsSelected property was modified.  Ignore all ancestors
            // who are merely reporting that a descendant's Selected fired.
            if (!Object.ReferenceEquals(sender, e.OriginalSource))
                return;

            var item = e.OriginalSource as ListBoxItem;
            if (item != null)
				item.BringIntoView();
                //((ListBox)item.Parent).ScrollIntoView(item);
        }

        #endregion // IsBroughtIntoViewWhenSelected
    }
}